package com.whmskj.xjlhbc.mobile.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhbc.domain.*;
import com.whmskj.xjlhbc.dto.EquipmentGroupDTO;
import com.whmskj.xjlhbc.dto.JtQueryDto;
import com.whmskj.xjlhbc.dto.ZjktQueryDto;
import com.whmskj.xjlhbc.mapper.Bcck05cjhssljlMapper;
import com.whmskj.xjlhbc.mobile.GetStartDate;
import com.whmskj.xjlhbc.service.ISb11dknittingstationstiedService;
import com.whmskj.xjlhbc.vo.GzinfoRecordVo;
import com.whmskj.xjlhbc.vo.WbInfoRecordVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SaIgnore
@RestController("appJtController")
@Tag(name = "机台列表",description = "机台列表")
@RequestMapping("/jt")
public class JtController {

    @Autowired
    private ISb11dknittingstationstiedService service;

    @Autowired
    private Bcck05cjhssljlMapper bcck05cjhssljlMapper;

    /**
     * 获取指定ID的故障详情记录
     *
     * @param id 故障记录ID
     * @return 返回AjaxResult封装的GzinfoRecordVo对象
     */
    @GetMapping("/gzinfoRecord/{id}")
    @Operation(description = "故障详情记录")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, GzinfoRecordVo.class})
    ))
    public AjaxResult gzinfoRecord(@PathVariable(name = "id") Integer id) {
        GzinfoRecordVo wbinfoRecord = service.gzinfoRecord(id);
        return AjaxResult.success(wbinfoRecord);
    }

    /**
     * 获取指定ID的维保详情记录
     *
     * @param id 维保记录ID
     * @return 返回AjaxResult封装的WbInfoRecordVo对象
     */
    @GetMapping("/wbinfoRecord/{id}")
    @Operation(description = "维保详情记录")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, WbInfoRecordVo.class})
    ))
    public AjaxResult wbinfoRecord(@PathVariable(name = "id") Integer id){
        WbInfoRecordVo wbinfoRecord = service.wbinfoRecord(id);
        return AjaxResult.success(wbinfoRecord);
    }

    /**
     * 根据ID和日期查询列表数据
     *
     * @param id 设备ID（可选）
     * @param date 查询日期（可选）
     * @return 返回分页封装的设备绑定记录列表
     */
    @GetMapping("/list")
    @Operation(description = "列表")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, Sb11dknittingstationstied.class})
    ))
    public AjaxResult list(@RequestParam(required = false) String id,@RequestParam(required = false) String date){
        List<Sb11dknittingstationstied> list = service.queryList(id,date);
        return Page.getDataTable(list);
    }

    /**
     * 织机看台数据查询
     *
     * @param param 查询参数对象，包含查询条件
     * @return 返回分页封装的织机计划表数据列表
     */
    @GetMapping("/zjkt")
    @Operation(description = "织机看台")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, Sc13dWrotePlannerTable.class})
    ))
    @Parameter(schema = @Schema(anyOf = {ZjktQueryDto.class}))
    public AjaxResult zjkt(ZjktQueryDto param){
        List<Sc13dWrotePlannerTable> list = service.zjktList(param);
        return Page.getDataTable(list);
    }

    /**
     * 查询维保记录列表
     *
     * @param param 查询参数对象，包含查询条件
     * @return 返回分页封装的维保计划列表
     */
    @GetMapping("/wbList")
    @Operation(description = "维保记录")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, By01MaintenanceSchedule.class})
    ))
    public AjaxResult wbList(JtQueryDto param){
        List<By01MaintenanceSchedule> list = service.wbList(param);
        return Page.getDataTable(list);
    }

    /**
     * 查询故障记录列表
     *
     * @param param 查询参数对象，包含查询条件
     * @return 返回分页封装的故障记录列表
     */
    @GetMapping("/gzList")
    @Operation(description = "故障记录")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, SchedulingOfSbbx01MalfunctionRep.class})
    ))
    public AjaxResult gzList(JtQueryDto param){
        List<SchedulingOfSbbx01MalfunctionRep> list = service.gzList(param);
        return Page.getDataTable(list);
    }

    /**
     * 统计指定时间段内的维保数据
     *
     * @param startTime 开始时间（格式：yyyy-MM-dd）
     * @param endTime 结束时间（格式：yyyy-MM-dd）
     * @return 返回封装统计结果的Map对象
     */
    @GetMapping("/wbtj")
    @Operation(description = "维保统计")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult wbtj(@RequestParam(name = "startTime")String startTime,
                           @RequestParam(name = "endTime") String endTime,
                           @RequestParam(name = "workshop", required = false) String workshop) {  // 添加车间ID参数
        Map<String, Object> map = service.wbtj(startTime, endTime, workshop);
        return AjaxResult.success(map);
    }

    /**
     * 统计指定时间段内的故障数据
     *
     * @param startTime 开始时间（格式：yyyy-MM-dd）
     * @param endTime 结束时间（格式：yyyy-MM-dd）
     * @return 返回封装统计结果的Map对象
     */
    @GetMapping("/gztj")
    @Operation(description = "故障统计")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult gztj(@RequestParam(name = "startTime")String startTime,
                           @RequestParam(name = "endTime") String endTime,
                           @RequestParam(name = "workshop", required = false) String workshop) {  // 添加车间ID参数
        Map<String, Object> map = service.gztj(startTime, endTime, workshop);
        return AjaxResult.success(map);
    }

    /**
     * 根据机台号查询维保单信息
     *
     * @param jth 机台号
     * @return 返回AjaxResult封装的维保计划对象
     */
    @GetMapping("/getWb")
    @Operation(description = "查询维保单")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, By01MaintenanceSchedule.class})
    ))
    public AjaxResult getWb(String jth){
        By01MaintenanceSchedule result = service.getWb(jth);
        return AjaxResult.success(result);
    }

    /**
     * 根据机台号查询故障单信息
     *
     * @param jth 机台号
     * @return 返回AjaxResult封装的故障记录对象
     */
    @GetMapping("/getGz")
    @Operation(description = "查询故障单")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, SchedulingOfSbbx01MalfunctionRep.class})
    ))
    public AjaxResult getGz(String jth){
        SchedulingOfSbbx01MalfunctionRep result = service.getGz(jth);
        return AjaxResult.success(result);
    }

    /**
     * 临时保存维保记录
     *
     * @param body 维保计划对象
     * @return 返回操作结果，成功或失败
     */
    @PostMapping("/addWbTemp")
    @Operation(description = "临时保存维保")
    public AjaxResult addWbTemp(@RequestBody By01MaintenanceSchedule body){
        boolean result = service.addWbTemp(body);
        if(result)
            return AjaxResult.success();
        return AjaxResult.error();
    }

    /**
     * 临时保存故障记录
     *
     * @param body 故障记录对象
     * @return 返回操作结果，成功或失败
     */
    @PostMapping("/addGzTemp")
    @Operation(description = "临时保存故障")
    public AjaxResult addGzTemp(@RequestBody SchedulingOfSbbx01MalfunctionRep body){
        boolean result = service.addGzTemp(body);
        if(result)
            return AjaxResult.success();
        return AjaxResult.error();
    }

    /**
     * 提交维保记录
     *
     * @param body 维保计划对象
     * @return 返回操作结果，成功或失败
     */
    @PostMapping("/addWb")
    @Operation(description = "提交维保")
    public AjaxResult addWb(@RequestBody By01MaintenanceSchedule body) {
        boolean result = service.addWb(body);
        if (result)
            return AjaxResult.success();
        return AjaxResult.error();
    }

    /**
     * 提交故障记录
     *
     * @param body 故障记录对象
     * @return 返回操作结果，成功或失败
     */
    @PostMapping("/addGz")
    @Operation(description = "提交故障记录")
    public AjaxResult addGz(@RequestBody SchedulingOfSbbx01MalfunctionRep body){
        boolean result = service.addGz(body);
        if(result)
            return AjaxResult.success();
        return AjaxResult.error();
    }

    /**
     * 查询机台号列表
     */
    @GetMapping("/getJthList")
    @Operation(description = "查询机台号列表")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult getEquipmentGroup(@RequestParam(required = false) String workshop) {
            List<EquipmentGroupDTO> result;

            if (StringUtils.isNotBlank(workshop)) {
                // 如果传入了车间参数，只查询指定车间
                result = service.getEquipmentByWorkshop(workshop);
            } else {
                // 如果没有传入车间参数，默认查询织布车间和准整车间
                result = service.getEquipmentByWorkshops(Arrays.asList("织布车间", "准整车间"));
            }

            return AjaxResult.success(result);
    }


    //品种开台
    @GetMapping("/pzkt")
    @Operation(description = "品种开台")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult pzkt() {
        Object result = service.pzkt();
        return AjaxResult.success(result);
    }

    //品种开台
    @GetMapping("/pzktDetail")
    @Operation(description = "品种开台详情")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult pzktDetail(@RequestParam String noNo) {
        Object result = service.pzktDetail(noNo);
        return AjaxResult.success(result);
    }

    // 了轴预测
    @GetMapping("/lzyc")
    @Operation(description = "了轴预测")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult lzyc() {
        Object result = service.lzyc();
        return AjaxResult.success(result);
    }

    //回丝日报
    @GetMapping("/dailyHs")
    @Operation(description = "回丝日报")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult dailyHs(String month) {
        String start = GetStartDate.getMonthStartDate().substring(0,10);
        String end = DateUtil.today();
        if(StringUtils.isNotEmpty(month)){
            LocalDate ld = LocalDate.parse(month+"-21").minusMonths(1);
            start = ld.withDayOfMonth(21).toString();
            end = LocalDate.parse(month+"-20").toString();
        }
        LambdaQueryWrapper<Bcck05cjhssljl> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(Bcck05cjhssljl::getStatisticsDate, start, end);
        wrapper.orderByDesc(Bcck05cjhssljl::getStatisticsDate);
        List<Bcck05cjhssljl> list = bcck05cjhssljlMapper.selectList(wrapper);
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> topMap = new HashMap<>();
        double sum = list.stream().mapToDouble(m -> NumberUtil.parseDouble(m.getZj1hs(), 0.0)).sum();
        double sum1 = list.stream().mapToDouble(m -> NumberUtil.parseDouble(m.getZj2lshs(), 0.0)).sum();
        double sum2 = list.stream().mapToDouble(m -> NumberUtil.parseDouble(m.getZj3zlhs(), 0.0)).sum();
        double sum3 = list.stream().mapToDouble(m -> NumberUtil.parseDouble(m.getJs1jhs(), 0.0)).sum();
        double sum4 = list.stream().mapToDouble(m -> NumberUtil.parseDouble(m.getJs2yhs(), 0.0)).sum();
        double sum5 = list.stream().mapToDouble(m -> NumberUtil.parseDouble(m.getZb1jhs(), 0.0)).sum();
        double sum6 = list.stream().mapToDouble(m -> NumberUtil.parseDouble(m.getZb2fbs(), 0.0)).sum();
        topMap.put("zj1", sum);
        topMap.put("zj2", sum1);
        topMap.put("zj3", sum2);
        topMap.put("js1", sum3);
        topMap.put("js2", sum4);
        topMap.put("zb1", sum5);
        topMap.put("zb2", sum6);
        result.put("top", topMap);
        result.put("tableList", list);
        return AjaxResult.success(result);
    }
}
